package geektime.concurrent.part2.blockingqueuedemo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;

public class NumberProducer implements Runnable {
    private BlockingQueue<Integer> queue;

    private int diamondPerProducer;

    private int diamondNumber;

    public NumberProducer(BlockingQueue queue, int diamondPerProducer, int diamondNumber) {
        this.queue = queue;
        this.diamondPerProducer = diamondPerProducer;
        this.diamondNumber = diamondNumber;
    }

    @Override
    public void run() {
        try {
            generateNumbers();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void generateNumbers() throws InterruptedException {
        // 先生产100个随机数放到queue中
        for (int i = 0; i < 100; i++) {
            // 注意：这里在往queue中添加数据的时候要使用put方法，使用add方法的话在size大于10后会抛出异常
            queue.put(ThreadLocalRandom.current().nextInt(100));
        }
        // 再生成 diamondPerProducer 个 diamondNumber
        for (int i = 0; i < diamondPerProducer; i++) {
            queue.put(diamondNumber);
        }
    }
}
